//
//  RegisterStep1ViewController.m
//  Voxper
//
//  Created by Erphan on 2/8/11.
//  Copyright 2011 Smonte. All rights reserved.
//

#import "RegisterStep1ViewController.h"
#import "CountriesListViewController.h"
#import "UIButton+Extra.h"
#import "WebProxy.h"
#import "RequestData.h"
#import "PassCodeViewController.h"
#import "VoxperAppDelegate.h"
#import "UIManager.h"
#import "Settings.h"
#import "Constants.h"
#import "RegexKitLite.h"

@interface RegisterStep1ViewController(Private)
- (void)requestLocation;
- (void)notificationReceived:(NSNotification *)note;
@end

@implementation RegisterStep1ViewController

- (id)initWithRegistrationOption:(BOOL)bIsNewCustomer {
    m_bIsNewCustomer = bIsNewCustomer;
    return [self initWithNibName:@"RegisterStep1ViewController" bundle:[NSBundle mainBundle]];
}

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
		app = (VoxperAppDelegate *)[UIApplication sharedApplication].delegate;
		[self requestLocation];
		[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(notificationReceived:) name:@"RegistrationCallback" object:nil];
		
		activity = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhite];
		activity.hidesWhenStopped = YES;
		
		UIBarButtonItem *barButton = [[UIBarButtonItem alloc] initWithCustomView:activity];
		[self.navigationItem setRightBarButtonItem:barButton animated:YES];
		[barButton release];
		
		m_strDefaultLocationPlaceHolder = @"Select location";
    }
    return self;
}

// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
    [super viewDidLoad];
	self.title = @"Setup";
	if ([app.uiManager.settings getRegistrationStepCompleted]) {
		PassCodeViewController *passCodeViewController = [[PassCodeViewController alloc] initWithNibName:@"PassCodeViewController" bundle:[NSBundle mainBundle]];
		[self.navigationController pushViewController:passCodeViewController animated:YES];
		[passCodeViewController release];
	}
    
    txtPhoneNumber = [[UITextField alloc] initWithFrame:CGRectMake(10, 10, 300, 45)];
    txtPhoneNumber.delegate = self;
    txtPhoneNumber.placeholder = @"Number without the country code";
    txtPhoneNumber.keyboardType = UIKeyboardTypePhonePad;
    
    txtVirtualNumber = [[UITextField alloc] initWithFrame:CGRectMake(10, 10, 300, 45)];
    txtVirtualNumber.delegate = self;
    txtVirtualNumber.placeholder = @"Enter virtual number";
    txtVirtualNumber.keyboardType = UIKeyboardTypePhonePad;
}

- (void)viewDidAppear:(BOOL)animated {
	[super viewDidAppear:animated];
	[m_TableView reloadData];
}


/*
// Override to allow orientations other than the default portrait orientation.
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    // Return YES for supported orientations.
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
*/

- (void)didReceiveMemoryWarning {
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc. that aren't in use.
}

- (void)viewDidUnload {
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}


- (void)dealloc {
	[[NSNotificationCenter defaultCenter] removeObserver:self];
	[activity release];
	[txtPhoneNumber release];
	[btnContinue release];
    [super dealloc];
}

#pragma mark -
#pragma mark IBAction

- (IBAction)btnContinue_Clicked {
	[txtPhoneNumber resignFirstResponder];
    [txtVirtualNumber resignFirstResponder];
    
    if ([[txtVirtualNumber text] length] < 5) {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:APP_NAME message:@"Incorrect virtual number" delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
		[alert show];
		[alert release];
    }
    
	if ([[app.uiManager.settings getMyLocation] length] == 0) {
		UIAlertView *alert = [[UIAlertView alloc] initWithTitle:APP_NAME message:@"Select your location" delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
		[alert show];
		[alert release];
	} else {
		NSString *strPhoneNumber = [app.uiManager convertPhoneNumberInIntlFormat:txtPhoneNumber.text :YES];
		UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Is this correct?" message:[NSString stringWithFormat:@"+%@", strPhoneNumber] delegate:self cancelButtonTitle:@"NO" otherButtonTitles:@"YES", nil];
		[alert show];
		[alert release];
	}
}

#pragma mark -
#pragma mark UIAlertViewDelegate
- (void)alertView:(UIAlertView *)alertView didDismissWithButtonIndex:(NSInteger)buttonIndex {
	if (buttonIndex == 1) {
		NSString *strPhoneNumber = [app.uiManager convertPhoneNumberInIntlFormat:txtPhoneNumber.text :YES];
		NSLog(@"%@", strPhoneNumber);
		NSLog(@"Number is correct");
		[app.uiManager.settings setUserName:strPhoneNumber];
        if (!m_bIsNewCustomer) {
            [app.uiManager registerPhone:strPhoneNumber withExistingVirtualNumber:[txtVirtualNumber text]];
        } else {
            [app.uiManager registerPhone:strPhoneNumber];
        }
		[activity startAnimating];
		txtPhoneNumber.enabled = NO;
		m_TableView.userInteractionEnabled = NO;
		btnContinue.enabled = NO;
	}
}

#pragma mark -
#pragma mark UITextField

- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    if ([txtPhoneNumber isFirstResponder]) {
        [textField resignFirstResponder];
    } else {
        [txtVirtualNumber resignFirstResponder];
    }
	return YES;
}

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
    
    NSUInteger newLength = [textField.text length] + [string length] - range.length;
    
	if ([textField.text length] >= 7) {
		btnContinue.enabled = YES;
	} else {
		btnContinue.enabled = NO;
	}

	return (newLength > 20) ? NO : YES;
}

#pragma mark -
#pragma mark TableView delegates

- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
	if ([txtPhoneNumber isFirstResponder]) {
        [txtPhoneNumber resignFirstResponder];
    } else {
        [txtVirtualNumber resignFirstResponder];
    }
}

- (NSIndexPath *)tableView:(UITableView *)tableView willSelectRowAtIndexPath:(NSIndexPath *)indexPath {
	[txtPhoneNumber resignFirstResponder];
	return indexPath;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (!m_bIsNewCustomer) {
        return 3;
    }
	return 2;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
	return 1;
}

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
    if (!m_bIsNewCustomer) {
        return @"Enter your phone number, VN# and press continue...";
    }
	return @"Enter your phone number and press continue...";
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
	return 100;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
	
	if (indexPath.row != 0) {
		return;
	}
	
	CountriesListViewController *viewController = [[CountriesListViewController alloc] initWithNibName:@"CountriesListViewController" bundle:[NSBundle mainBundle]];
	[self.navigationController pushViewController:viewController animated:YES];
	[viewController release];
	[tableView deselectRowAtIndexPath:indexPath animated:YES];
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
	
	UIView *footerView = [[[UIView alloc] initWithFrame:CGRectMake(0, 0, 320, 100)] autorelease];
	
	//btnContinue = [[UIButton alloc] initWithFrame:CGRectMake(10, 10, 300, 42)];
    btnContinue = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    [btnContinue setTitle:@"Continue" forState:UIControlStateNormal];
	btnContinue.frame = CGRectMake(10, 10, 300, 42);
	//btnContinue.backgroundColor = [UIColor clearColor];
	//[btnContinue setImage:[UIImage imageNamed:@"btn_continue.png"] forState:UIControlStateNormal];
	[btnContinue addTarget:self action:@selector(btnContinue_Clicked) forControlEvents:UIControlEventTouchUpInside];
	
	if ([txtPhoneNumber.text length] >= 7) {
		btnContinue.enabled = YES;
	} else {
		btnContinue.enabled = NO;
	}

//	UILabel *lblFooterNote = [[[UILabel alloc] initWithFrame:CGRectMake(10, 45, 300, 40)] autorelease];
//	lblFooterNote.text = @"A pin code will be sent on your phone.";
//	lblFooterNote.backgroundColor = [UIColor clearColor];
//	lblFooterNote.font = [UIFont systemFontOfSize:11];
//	lblFooterNote.textAlignment = UITextAlignmentCenter;
//	lblFooterNote.shadowColor = [UIColor whiteColor];
//	lblFooterNote.shadowOffset = CGSizeMake(0, 1);
//	lblFooterNote.textColor = [UIColor darkGrayColor];
//	
//	[footerView addSubview:lblFooterNote];
	[footerView addSubview:btnContinue];
	
	return footerView;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
	static NSString *CellIdentifier = @"RegisterStep1CellIdent";
	
	UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
	
	if (cell == nil) {
		cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
		if (indexPath.row == 0 && indexPath.section == 0) {
			cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
		}
    }
	
	switch (indexPath.section) {
		case 0:
			switch (indexPath.row) {
				case 0:
					if ([[app.uiManager.settings getMyLocation] length] < 1) {
						cell.textLabel.text = m_strDefaultLocationPlaceHolder;
					} else {
						cell.textLabel.text = [NSString stringWithFormat:@"%@ (+%@)", [app.uiManager.settings getMyLocation], [app.uiManager.settings getMyLocationCode]];
					}
					break;
				case 1:
				{
					[cell.contentView addSubview:txtPhoneNumber];
					cell.selectionStyle = UITableViewCellSelectionStyleNone;
                    break;
				}
                case 2:
                    [[cell contentView] addSubview:txtVirtualNumber];
                    [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
					break;
				default:
					break;
			}
			break;
		default:
			break;
	}
	
	
	
	return cell;
}

#pragma mark -
#pragma mark Private

- (void)requestLocation {
	[app.uiManager updateMyLocation];
	[activity startAnimating];
}

- (void)notificationReceived:(NSNotification *)note {	
	[activity stopAnimating];
	txtPhoneNumber.enabled = YES;
	m_TableView.userInteractionEnabled = YES;
	btnContinue.enabled = NO;
	
	[txtPhoneNumber resignFirstResponder];
	
	if ([note object]) {
		NSString *strInfo = (NSString *)[note object];
		if ([strInfo isEqualToString:@"Registered"]) {
			PassCodeViewController *passCodeViewController = [[PassCodeViewController alloc] initWithNibName:@"PassCodeViewController" bundle:[NSBundle mainBundle]];
			[self.navigationController pushViewController:passCodeViewController animated:YES];
			[passCodeViewController release];
			[app.uiManager.settings setRegistrationStepCompleted:YES];
		} else if ([strInfo isEqualToString:@"LocationFailed"]) {
			m_strDefaultLocationPlaceHolder = @"Select your location";
			[m_TableView reloadData];
		} else {
			UIAlertView *alert = [[UIAlertView alloc] initWithTitle:APP_NAME message:strInfo delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
			[alert show];
			[alert release];
            btnContinue.enabled = YES;
		}


	} else {
		[m_TableView reloadData];
	}
}

@end
